package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"strconv"
	"strings"

	"github.com/garyburd/redigo/redis"

	"github.com/wtf/mahjong/model"
	"github.com/wtf/mahjong/utils"
)

func checkUnion(openId string) (unionOpenId string, code int) {
	resp, err1 := http.Get("http://gc-api.ledongtian.com/customerService/public/mahjong/check_union?openid=" + openId)
	if err1 != nil {
		utils.Error("unionCheck err", err1)
		return "", 301
	}

	defer resp.Body.Close()
	body, err2 := ioutil.ReadAll(resp.Body)
	if err2 != nil {
		utils.Error("unionCheck err", err2)
		return "", 302
	}

	response := model.CheckResponse{}
	err3 := json.Unmarshal(body, &response)
	if err3 != nil {
		utils.Error("unionCheck err", err3)
		return "", 303
	}

	// 判断是否提现成功
	if response.Code != 0 {
		utils.Error("unionCheck err", response.Msg)
		return "", 303
	}

	return response.Data, 0
}

func drawMahjongFunc(openId, sign string, types int) (code int, err error) {
	locksss.Lock()
	defer locksss.Unlock()

	code = 0
	api := "draw_mahjong"
	if types == 1 {
		api = "draw_mahjong2"
	}
	resp, err1 := http.Get("http://gc-api.ledongtian.com/block_php_server/public/api/" + api + "?openId=" + openId + "&sign=" + sign)
	if err1 != nil {
		code = 114
		err = errors.New("无法获取接口信息")
		return
	}

	defer resp.Body.Close()
	body, err2 := ioutil.ReadAll(resp.Body)
	if err2 != nil {
		code = 111
		err = errors.New("无法获取接口data信息")
		return
	}

	response := model.DrawResponse{}
	err3 := json.Unmarshal(body, &response)
	if err3 != nil {
		code = 112
		err = errors.New("无法解析body信息")
		return
	}

	// 判断是否提现成功
	if response.Code != 0 {
		code = 113
		err = errors.New(response.Msg)
		return
	}
	return code, nil
}

func arr2Str(arr []string) string {
	return strings.Replace(strings.Trim(fmt.Sprint(arr), "[]"), " ", ",", -1)
}

func post(data model.Qrcode) (png []byte, err error) {
	bytes, _ := json.Marshal(data)
	client := &http.Client{}

	// 从池里获取连接
	rc := model.RedisClient.Get()
	// 用完后将连接放回连接池
	defer rc.Close()

	s, err := redis.String(rc.Do("get", "customerServiceMahjong:accessToken"))
	if err != nil {
		return
	}

	tokenData := model.Token{}
	err = json.Unmarshal([]byte(s), &tokenData)
	if err != nil {
		return
	}

	url := "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + tokenData.AccessToken
	req, err := http.NewRequest("POST", url, strings.NewReader(string(bytes)))
	if err != nil {
		return
	}

	req.Header.Set("Content-Type", "application/octet-stream")

	resp, err := client.Do(req)

	defer resp.Body.Close()

	png, err = ioutil.ReadAll(resp.Body)
	return
}

func rRand(min, max int, r *rand.Rand) int {
	return min + r.Intn(max-min+1)
}

func getQueueStr(cardInfo model.CardInfo, redId int) (queueStr string) {
	switch redId {
	case 1:
		queueStr = cardInfo.C1
	case 2:
		queueStr = cardInfo.C2
	case 3:
		queueStr = cardInfo.C3
	case 4:
		queueStr = cardInfo.C4
	case 5:
		queueStr = cardInfo.C5
	case 6:
		queueStr = cardInfo.C6
	case 7:
		queueStr = cardInfo.C7
	}

	return
}

func getColumn(redId int) (column string) {
	switch redId {
	case 1:
		column = "C1"
	case 2:
		column = "C2"
	case 3:
		column = "C3"
	case 4:
		column = "C4"
	case 5:
		column = "C5"
	case 6:
		column = "C6"
	case 7:
		column = "C7"
	}

	return
}

func createStr(cardId, redId int) string {
	arr := make([]int, 10)
	arr[cardId] = 1
	if redId > 3 {
		x := randInt64(1, 3)

		for i := x; i > 0; i-- {
			y := 9
			for {
				y = int(randInt64(1, 9))
				if y != cardId {
					break
				}

			}
			arr[y] = 777
		}
	}
	return strings.Replace(strings.Trim(fmt.Sprint(arr), "[]"), " ", ",", -1)
}

func DecRed(row []string) string {
	newRow := make([]int, len(row))
	for key, id := range row {
		if key == 0 {
			newRow[key] = 0
		} else {
			idInt, _ := strconv.Atoi(id)
			newRow[key] = idInt - 1
		}
	}

	return strings.Replace(strings.Trim(fmt.Sprint(newRow), "[]"), " ", ",", -1)
}

func checkRed(row []string) bool {
	res := true
	for key, id := range row {
		idInt, _ := strconv.Atoi(id)
		if key > 0 && idInt <= 0 {
			res = false
			break
		}
	}

	return res
}
